﻿using AutoMapper;
using Domain.Production_Modules;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Production_Modules.MaterialOutAsk;
using ReturnValue;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Handler.Production_Modules.MaterilaOutAsk
{
    public class AddMaterialOutAskHander : IRequestHandler<AddMaterialOutAskCommand, ApiResult<int>>
    {
        private readonly IRepository<MaterialOutAskModel> materialOutAskRepo;
        private readonly IMapper mapper;
        public AddMaterialOutAskHander(IRepository<MaterialOutAskModel> materialOutAskRepo, IMapper mapper)
        {
            this.materialOutAskRepo = materialOutAskRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 物料入库申请单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddMaterialOutAskCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();
            var Ask = materialOutAskRepo.GetAll().Where(x => x.OutAskCode == request.OutAskCode).FirstOrDefault();
            if(Ask != null)
            {
                result.Message = "物料出库申请单号已存在,无法重复申请";
                result.Code = StatusCode.Fail;
                return await Task.FromResult(result);
            }
            var zhi = mapper.Map<MaterialOutAskModel>(request);
            zhi.Id = YitIdHelper.NextId();
            zhi.IsDel = false;
            zhi.CreateTime = DateTime.Now;  
            if(zhi!=null)
            {
                await materialOutAskRepo.AddAsync(zhi);
                result.Code = StatusCode.Success;
                result.Message = "物料入库申请成功";
                return await Task.FromResult(result);
            }
            else
            {
                result.Code = StatusCode.Fail;
                result.Message = "物料入库申请失败";
                return await Task.FromResult(result);
            }
        }
    }
}
